package com.yuyu.qingmangmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyu.common.utils.HttpUtils;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.qingmangmall.member.dao.MemberDao;
import com.yuyu.qingmangmall.member.dao.MemberLevelDao;
import com.yuyu.qingmangmall.member.entity.MemberEntity;
import com.yuyu.qingmangmall.member.entity.MemberLevelEntity;
import com.yuyu.qingmangmall.member.exception.EmailExistException;
import com.yuyu.qingmangmall.member.exception.UsernameExistException;
import com.yuyu.qingmangmall.member.service.MemberService;
import com.yuyu.qingmangmall.member.vo.MemberLoginVo;
import com.yuyu.qingmangmall.member.vo.MemberRegisterVo;
import com.yuyu.qingmangmall.member.vo.SocialUser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo registerVo) {

        MemberEntity memberEntity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;

        MemberLevelEntity memberLevel = memberLevelDao.selectDefaultLevel();
        memberEntity.setLevelId(memberLevel.getId()); //设置注册时的默认等级


        // 判断数据库中用户名和邮箱是否唯一 为了让Controller感知到  通过异常机制  不唯一抛出异常
        String email = registerVo.getEmail();
        String userName = registerVo.getUserName();
        checkEmailUnique(email);
        checkUsernameUnique(userName);

        memberEntity.setEmail(email);
        memberEntity.setUsername(userName);

        // 数据库加密
        String password = registerVo.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        memberEntity.setPassword(encode);

        // 默认值

        // 保存到数据库
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException{
        Integer nameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (nameCount>0){
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkEmailUnique(String email) throws EmailExistException {
        Integer emailCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("email", email));
        if (emailCount>0){
            throw new EmailExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {

        String loginAcct = memberLoginVo.getLoginacct(); // 前端传来的 用户名或email
        String password = memberLoginVo.getPassword(); // 前端传来的 密码

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("email", loginAcct));
        if (memberEntity!=null){
            // 匹配到账号对应的用户
            String entityPassword = memberEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            // 将数据库中的密码和传入的密码进行匹配
            boolean matches = encoder.matches(password, entityPassword);
            if (matches){ // 密码匹配成功
                return memberEntity;
            }else {
                // 密码匹配失败
                return null;
            }
        }else {
            // 没有匹配到账号对应的用户
            return null;
        }

    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) throws Exception {
        // 注册或登录
        String uid = socialUser.getUid();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity!=null){
            // 该社交账号注册过商城会员 ，更新accessToken和 expiresIn（令牌过期时间）
            // accessToken应放在redis中，过期时间设置为 expiresIn  key-value  uid-accessToken
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            // 更新数据库
            String expires_inString = Long.toString(socialUser.getExpires_in());
            update.setExpiresIn(expires_inString);
            memberDao.update(update,new UpdateWrapper<MemberEntity>().eq("id",update.getId()));

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(expires_inString);
            return memberEntity;

        }else {
            // 该社交账号没有注册过商城会员,需要注册一个
            MemberEntity regist = new MemberEntity();

            try {
                // 查询当前社交用户的社交帐号信息（昵称，性别等）
                Map<String,String> querys = new HashMap<>();
                querys.put("access_token",socialUser.getAccess_token());
                querys.put("uid",socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", null, new HashMap<String, String>(), querys);
                if (response.getStatusLine().getStatusCode()==200){ // 查询成功
                    HttpEntity entity = response.getEntity();
                    String entityString = EntityUtils.toString(entity);
                    JSONObject jsonObject = JSON.parseObject(entityString);
                    // 昵称，性别等
                    String screen_name = jsonObject.getString("screen_name");
                    String gender = jsonObject.getString("gender"); // m w
                    // 。。。。
                    regist.setNickname(screen_name);
                    regist.setGender("m".equals(gender)?1:0);
                    MemberLevelEntity memberLevel = memberLevelDao.selectDefaultLevel();
                    regist.setLevelId(memberLevel.getId()); //设置注册时的默认等级
                    // 。。。。

                }
            }catch (Exception e){

            }

            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            String expires_inString = Long.toString(socialUser.getExpires_in());
            regist.setExpiresIn(expires_inString);

            memberDao.insert(regist);
            return regist;

        }
    }

}